package com.xjy.system.service;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Service;

import com.xjy.common.core.domain.model.LoginUser;
import com.xjy.system.domain.SysFundaccount;
import com.xjy.system.domain.SysFundaccountLog;
import com.xjy.system.domain.SysPayaccount;
import com.xjy.system.repository.SysFundaccountLogRepository;
import com.xjy.system.repository.SysFundaccountRepository;
import com.xjy.system.repository.SysPayaccountRepository;

@Service
public class ProductHelpService {
	
	@Autowired
	private SysFundaccountRepository sysFundaccountRepository;
	
	@Autowired
	private SysPayaccountRepository sysPayaccountRepository;
	
	@Autowired
	private SysFundaccountLogRepository sysFundaccountLogRepository;
	
	@Autowired
    private HttpServletRequest request;

	/**
	 * 根据当前时间判断指定项目是否已结账
	 * @param proid
	 * @return
	 */
	public boolean mayUse(long proid) {
		return this.mayUse(proid, new Date());
	}
	/**
	 * 根据指定时间判断指定项目是否已结账
	 * @param proid
	 * @param time
	 */
	public boolean mayUse(long proid,Date time) {
		return true;
	}
	
	/**
	 * 金额减少
	 * @param countId 帐户id
	 * @param proid  项目id
	 * @param type 类型，0未知 1押金
	 * @param money  变更金额
	 * @param remark 备注
	 */
	public void subtractMoney(long countId,long proid,int type,BigDecimal money,String remark) {
		if(!this.sysFundaccountRepository.existsById(countId)) {
			SysFundaccount sf = new SysFundaccount();
			SysPayaccount sp = this.sysPayaccountRepository.getOne(countId);
			sf.setAccountId(sp.getAccountId());
			sf.setAccountBank(sp.getAccountBank());
			sf.setAccountFistbalance(BigDecimal.ZERO);
			sf.setAccountLastbalance(BigDecimal.ZERO);
			sf.setAccountName(sp.getAccountName());
			sf.setAccountPhone(sp.getAccountPhone());
			sf.setId(sp.getId());
			this.sysFundaccountRepository.save(sf);
		}
		SysFundaccount sfc = this.sysFundaccountRepository.getOne(countId);
		
		SysFundaccountLog sfl = new SysFundaccountLog();
		sfl.setPrevMoney(sfc.getAccountLastbalance());
		
		sfc.setAccountLastbalance(sfc.getAccountLastbalance().subtract(money, MathContext.UNLIMITED));
		this.sysFundaccountRepository.save(sfc);
		
		sfl.setLastMoney(sfc.getAccountLastbalance());
		sfl.setAccountId(countId);
		sfl.setMoney(money);
		sfl.setProjId(proid);
		sfl.setRemark(remark);
		sfl.setTime(new Date());
		sfl.setType(type);
		sfl.setUserId(((LoginUser)((UsernamePasswordAuthenticationToken)request.getUserPrincipal()).getPrincipal()).getUser().getUserId());
		this.sysFundaccountLogRepository.save(sfl);
	}
	
}
